# minio_client.py
from minio import Minio
from minio.error import S3Error
from configs import get_config
# from config import MINIO_ENDPOINT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY, MINIO_SECURE, BUCKET_NAME


def ensure_bucket():
    """确保 bucket 存在"""

    config = get_config()
    
    print(f"config: {config}")
    
    client = Minio(
        config['minio']['endpoint'],
        access_key=config['minio']['access_key'],
        secret_key=config['minio']['secret_key'],
        secure=config['minio']['secure']
    )
    try:
        BUCKET_NAME = config['minio']['bucket_name']
        
        if not client.bucket_exists(BUCKET_NAME):
            client.make_bucket(BUCKET_NAME)
            print(f"✅ MinIO bucket '{BUCKET_NAME}' 创建成功")
        
        print(f"✅ MinIO bucket '{BUCKET_NAME}' 已存在")
    except S3Error as e:
        print(f"❌ 创建 bucket 失败: {e}")
        raise

def upload_file(local_path: str, object_name: str) -> str:
    """
    上传文件到 MinIO
    """
    try:
        config = get_config()

        client = Minio(
            config['minio']['endpoint'],
            access_key=config['minio']['access_key'],
            secret_key=config['minio']['secret_key'],
            secure=config['minio']['secure']
        )
        
        BUCKET_NAME = config['minio']['bucket_name']

        client.fput_object(
            BUCKET_NAME,
            object_name,
            local_path,
            content_type="image/jpeg" if object_name.lower().endswith(('.jpg', '.jpeg')) else "video/mp4"
        )
        return f"s3://{BUCKET_NAME}/{object_name}"
    except Exception as e:
        print(f"❌ 上传失败 {object_name}: {e}")
        return None